import json
import random
import uuid
import requests
from django.core.files.storage import default_storage
from django.shortcuts import render
from django.views.decorators.http import require_POST, require_GET
from datetime import datetime, timedelta

from apps.base.logMsg import logMsg
from apps.menu.models import MenuType, Menu, MenuItem
from apps.menu.serializers import MenuTypeSerializer, MenuSerializer, MenuItemSerializer
from apps.users.models import Users
from order.jsonresp import JSONResponse


# Create your views here.

@require_GET
def carousel(request):
    images = list(Menu.objects.values_list('image', flat=True))
    random_ids = random.sample(images, min(5, len(images)))
    return JSONResponse(code=0, data={
        "items": random_ids,
        "total": len(random_ids)
    })


@require_POST
def menu_type_add(request):
    try:
        json_data = json.loads(request.body)
    except Exception as e:
        json_data = {}
    operator = json_data.get('operator')
    if not operator:
        return JSONResponse(code=10000, message="请登录")
    operator_obj = Users.objects.filter(id=operator).first()
    if not operator_obj:
        return JSONResponse(code=10000, message="请登录")
    json_data["operator"] = operator_obj.id
    ser = MenuTypeSerializer(data=json_data)
    if ser.is_valid():
        ser.save()
        return JSONResponse(code=0)
    logMsg().error(str(ser.errors))
    return JSONResponse(code=10000, message=str(ser.errors))


@require_GET
def menu_type_del(request):
    json_data = request.GET
    id = json_data.get('id')
    MenuType.objects.filter(id=id).delete()
    return JSONResponse(code=0)


@require_GET
def menu_type_list(request):
    type_ = MenuType.objects.values("id", "name")
    return JSONResponse(code=0, data={
        "items": list(type_),
        "total": len(type_)
    })


@require_POST
def menu_add(request):
    try:
        json_data = json.loads(request.body)
    except Exception as e:
        json_data = {}
    operator = json_data.get('operator')
    if not operator:
        return JSONResponse(code=10000, message="请登录")
    operator_obj = Users.objects.filter(id=operator).first()
    if not operator_obj:
        return JSONResponse(code=10000, message="请登录")
    json_data["operator"] = operator_obj.id
    ser = MenuSerializer(data=json_data)
    if ser.is_valid():
        ser.save()
        return JSONResponse(code=0)
    logMsg().error(str(ser.errors))
    return JSONResponse(code=10000, message=str(ser.errors))


@require_GET
def menu_del(request):
    json_data = request.GET
    id = json_data.get('id')
    Menu.objects.filter(id=id).delete()
    return JSONResponse(code=0)


@require_POST
def menu_edit(request):
    pass


@require_GET
def menu_list(request):
    try:
        json_data = request.GET
    except Exception as e:
        json_data = {}
    type_ = json_data.get("type")
    name = json_data.get("name")
    con = {}
    if type_:
        con["type"] = type_
    if name:
        con["name__contains"] = name
    menu_ = Menu.objects.filter(**con).values()
    return JSONResponse(code=0, data={
        "items": list(menu_),
        "total": len(menu_)
    })


@require_POST
def menu_upload(request):
    image = request.FILES.get('files')
    # 生成一个唯一的文件名
    file_name = f"{uuid.uuid4()}.jpg"  # 根据需要更改扩展名
    file_path = f"uploads/{file_name}"  # 指定保存路径

    # 保存文件
    default_storage.save(file_path, image)
    return JSONResponse(code=0, data={
        "image": "https://sichu.maer.asia/media/" + file_path,
    })


@require_POST
def menu_submit(request):
    try:
        json_data = json.loads(request.body)
    except Exception as e:
        json_data = {}
    menu = json_data.get('menu')
    operator = json_data.get('operator')
    notes = json_data.get("notes")
    chef = Users.objects.filter(id=operator).first()
    if not operator:
        return JSONResponse(code=10000, message="请登录")
    json_data["user"] = chef.id
    json_data["chef"] = Users.objects.filter(openid=chef.chef).first().id
    ser = MenuItemSerializer(data=json_data)
    if ser.is_valid():
        ser.save()
        send_message(operator, menu, notes)
        return JSONResponse(code=0)
    logMsg().error(str(ser.errors))
    return JSONResponse(code=10000, message=str(ser.errors))


def send_message(user_id, menu_ids, notes):
    current_datetime = datetime.now()
    future_time = current_datetime + timedelta(hours=8)
    formatted_datetime = future_time.strftime("%Y-%m-%d %H:%M:%S")
    user_info = Users.objects.filter(id=user_id).first()
    menus = list(Menu.objects.filter(id__in=menu_ids).values_list("name", flat=True))
    openid = user_info.openid
    chef = user_info.chef
    chef_in = Users.objects.filter(openid=chef).first().name
    url = ("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}"
           .format('wxefb9f13917f7eca9', '90a8cbeba423052532b07a5bfa1c31cd'))
    res = requests.get(url)
    token = res.json()['access_token']
    headers = {"Content-Type": "application/json"}
    ding = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={}".format(token)
    d = {
        "touser": openid,
        "template_id": "-9b_AUjeM7WOdDe0W8mD0GyBD_9pf3zSySMo-jW0zlY",
        "lang": 'zh_CN',
        "miniprogramState": 'developer',

        "data": {
            "thing2": {
                "value": "马氏餐馆"
            },

            "thing15": {
                "value": str(chef_in) + "家里"
            },
            "thing6": {
                "value": ','.join(menus)
            },
            "time7": {
                "value": formatted_datetime
            },
            "thing5": {
                "value": notes if notes else 0
            }
        }
    }
    re = requests.post(ding, headers=headers, data=json.dumps(d))
    logMsg().info("my_send" + str(re.text))


@require_GET
def menu_items(request):
    json_data = request.GET
    user_id = json_data.get("operator")
    type = json_data.get("type")
    con = {"user_id": user_id}
    if int(type) == 1:
        con = {"chef_id": user_id}
    m_obj = MenuItem.objects.filter(**con)
    result = []
    for x in m_obj:
        result.append({
            "id": x.id,
            "menu": ','.join([y.name for y in x.menu.all()]),
            "user": x.user.name,
            "chef": x.chef.name,
            "create_date": (x.create_date + timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"),
        })
    return JSONResponse(code=0, data={
        "items": result,
        "total": len(result)
    })


@require_GET
def menu_items_del(request):
    id = request.GET.get("id")
    operator = request.GET.get('operator')
    if not operator:
        return JSONResponse(code=10000, message="请登录")
    operator_obj = Users.objects.filter(id=operator).first()
    if not operator_obj:
        return JSONResponse(code=10000, message="请登录")
    MenuItem.objects.filter(id=id).filter().delete()
    return JSONResponse(code=0)
